#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
from django.db import models
from Task.models import Task
from django.db.models.signals import post_delete
from django.core.files.base import ContentFile
from cStringIO import StringIO
from django.dispatch import receiver
import json
import copy

DEFAULT_KEYWORD_CONF = {
    'orders': ['general', 'popular', 'sales'],
    'tmall': True
}


class KeywordTask(models.Model):
    keyword = models.CharField(max_length=255, unique=True, db_index=True)

    tasks = models.ManyToManyField(Task, null=True, blank=True)

    updated = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        is_add = self._state.adding
        super(KeywordTask, self).save(*args, **kwargs)
        assert self.keyword, 'keyword is not assign'

        if is_add:
            self.create_tasks()
            self.save()

    def create_tasks(self):
        keyword = self.keyword

        o_data = {}
        o_data['keyword'] = keyword
        orders = ['general', 'popular', 'sales']
        tmall_options = [True, False]

        for order in orders:
            for tmall_option in tmall_options:
                data = copy.deepcopy(o_data)
                data['order_by'] = order
                data['tm_only'] = tmall_option
                pc_name = u"{}_{}_{}_pc_".format(keyword, order, tmall_option)

                mobile_name = u"{}_{}_{}_mobile_".format(
                    keyword, order, tmall_option)

                data['limit'] = 604
                pc_ranking = Task.objects.update_or_create(
                    name=pc_name + "ranking", raw_conf=json.dumps(data), module='esr_parser.jobs.get_pc_ranking', live=True)[0]
                data['limit'] = 200
                mobile_ranking = Task.objects.update_or_create(
                    name=mobile_name + "ranking", raw_conf=json.dumps(data), module='esr_parser.jobs.get_mobile_ranking', live=True)[0]

                data = {"limit": 84, "comments": 0}
                pc_ranking_detail = Task.objects.update_or_create(
                    name=pc_name + "ranking_detail", raw_conf=json.dumps(data), module='esr_parser.jobs.get_ranking_item_detail', live=True)[0]

                pc_ranking_detail.dependence.add(pc_ranking)
                pc_ranking_detail.save()

                mobile_ranking_detail = Task.objects.update_or_create(
                    name=mobile_name + "ranking_detail", raw_conf=json.dumps(data), module='esr_parser.jobs.get_ranking_item_detail', live=True)[0]

                mobile_ranking_detail.dependence.add(mobile_ranking)
                mobile_ranking_detail.save()

                self.tasks.add(pc_ranking)
                self.tasks.add(pc_ranking_detail)
                self.tasks.add(mobile_ranking)
                self.tasks.add(mobile_ranking_detail)


@receiver(signal=post_delete, sender=KeywordTask)
def stop_keyword_task(sender, instance, **kwargs):
    instance.tasks.all().update(live=False)


class ProductListTask(models.Model):
    name = models.CharField(max_length=1024, db_index=True)
    product_list = models.TextField()
    task = models.ForeignKey(Task, null=True, related_name='productlist')
    comment_limit = models.IntegerField(default=500)
    updated = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        is_add = self._state.adding
        super(ProductListTask, self).save(*args, **kwargs)

        if is_add:
            self.create_task()
            self.save()

    def create_task(self):
        task, is_add = Task.objects.get_or_create(name=self.name)
        if not is_add:
            assert task.module == 'esr_parser.jobs.get_product_list_items'
            assert task.live == False
            task.live = True
        task.module == 'esr_parser.jobs.get_product_list_items'
        task.save()
        self.task = task



@receiver(post_delete, sender=ProductListTask)
def stop_product_list_task(sender, instance, **kwargs):
    task = instance.task
    if not task:
        return
    task.live = False
    task.save()


def ranking_path(instance, filename):
    from datetime import datetime
    return datetime.now().strftime('screenshot/%Y_%m_%d/{}'.format(filename))

class RankingScreenShot(models.Model):
    name = models.CharField(max_length=2048)
    page = models.IntegerField(default=0)
    content = models.ImageField(upload_to=ranking_path)
    date = models.DateField(auto_now_add=True)

    @classmethod
    def create(cls, name, screenshot, page=0):
        self = cls()
        img = ContentFile(screenshot)
        self.content.save("{}_{}.png".format(name.encode('utf-8'), page), img)
        self.name = name
        self.page = page
        self.save()
